/**
 * 2018年12月9日下午2:28:50
 * @author 谢进财
 */
package com.baihang.project.ds.service;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.CellType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.util.TypeUtils;
import com.baihang.framework.dao.Record;
import com.baihang.framework.kit.DateKit;
import com.baihang.framework.kit.DownLoadKit;
import com.baihang.framework.kit.JsonKit;
import com.baihang.framework.kit.PathKit;
import com.baihang.framework.kit.database.RedisKit;
import com.baihang.framework.service.BaseService;
import com.baihang.project.ds.config.SystemConfig;
import com.baihang.project.ds.dao.CollectionMonitorDao;
import com.baihang.project.ds.dao.FangYuanDao;
import com.baihang.project.ds.entity.RoomCollectionEntity;
import com.baihang.project.ds.model.FangYuanModel;

import redis.clients.jedis.Jedis;

/**
 * @author whati
 *
 */
@Service
public class CollectionMonitorService extends BaseService {
	private static Logger logger = LoggerFactory.getLogger(CollectionMonitorService.class);
	private Jedis jedis = RedisKit.getJedis();
	@Autowired
	private CollectionMonitorDao dao;
	@Autowired
	private FangYuanDao  fyDao;
	public String collectionUpdate(String type,String id,String count) {
		List<Record> records = new ArrayList<Record>();//存放返回的需要变色的数据
		Random random = new Random();
		if("1".equals(type)) {//单个房源
			dao.update(String.format("update room set D_CollectionCount=%d where D_ID=%d", Integer.valueOf(count),Integer.valueOf(id)));							
			records = dao.queryForRecordList(String.format("select D_ID ,D_CollectionCount  from room  where D_ID=%d", Integer.parseInt(id)));
		}else {
			List<Record> list = new ArrayList<Record>();
			String[]  parems = id.split("-");
			if("2".equals(type)) {//楼栋
				if("0".equals(count)) {
					dao.update(String.format("update room set D_CollectionCount=0 where D_BanName='%s'", id));					
				}else {
					list = dao.queryForRecordList(String.format("select D_ID  from room where D_BanName='%s'", id));					
				}
				
			}else if("3".equals(type)) {//单元
				if("0".equals(count)) {
					dao.update(String.format("update room set D_CollectionCount=0 where D_BanName='%s' and D_Unit='%s'", parems[0],parems[1]));
				}else {
					list = dao.queryForRecordList(String.format("select D_ID from room where D_BanName='%s' and D_Unit='%s'", parems[0],parems[1]));					
				}
			}else {//套型
				if("0".equals(count)) {
					dao.update(String.format("update room set D_CollectionCount=0 where D_BanName='%s' and D_Unit='%s' and D_position='%s'", parems[0],parems[1],parems[2]));
				}else {
					list = dao.queryForRecordList(String.format("select D_ID from room where D_BanName='%s' and D_Unit='%s' and D_position='%s'", parems[0],parems[1],parems[2]));									
				}
			}
			long updateCount = 0;
			if(list.size()>0) {
				for(Record rec : list) {
					updateCount = random.nextInt(Integer.valueOf(count));//根据指定的范围随机增加收藏数		
					dao.update(String.format("update room set D_CollectionCount=%d where D_ID=%d", updateCount,rec.getInt("D_ID")));																
				}
			}
			//变更记录返回
			if("2".equals(type)) {
				records = dao.queryForRecordList(String.format("select D_ID as id,D_CollectionCount as dcollection from room  where D_BanName='%s'", id));
			}else if("3".equals(type)) {//单元
				records = dao.queryForRecordList(String.format("select D_ID as id,D_CollectionCount as dcollection from room where D_BanName='%s' and D_Unit='%s'", parems[0],parems[1]));

			}else{//套型
				records = dao.queryForRecordList(String.format("select D_ID as id,D_CollectionCount as dcollection  from room where D_BanName='%s' and D_Unit='%s' and D_position='%s'", parems[0],parems[1],parems[2]));						
			}
			SystemConfig.collectionConfig.put(id, count);//存放收藏数据，使下次点击可以直接读取			
		}
		
		return JsonKit.toDoubleJson2("true", JsonKit.listToJson(records, 1));
	}
	//同步redis上的收收藏
	public String collectionUpdateForRedis(String type,String id,String count) {
		Random random = new Random();
		if("1".equals(type)) {//单个房源
			String modelJson = jedis.hmget("rooms", id).get(0);
			FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
			model.setD_CollectionCount(Integer.valueOf(count));
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(id), JSON.toJSONString(model));
		}else {
			List<Record> list = new ArrayList<Record>();
			String[]  parems = id.split("-");
			if("2".equals(type)) {//楼栋
			
					list = dao.queryForRecordList(String.format("select D_ID  from room where D_BanName='%s'", id));					
				
				
			}else if("3".equals(type)) {//单元
				
			
					list = dao.queryForRecordList(String.format("select D_ID from room where D_BanName='%s' and D_Unit='%s'", parems[0],parems[1]));					
				
			}else {//套型
				
					list = dao.queryForRecordList(String.format("select D_ID from room where D_BanName='%s' and D_Unit='%s' and D_position='%s'", parems[0],parems[1],parems[2]));									
				
			}
			long updateCount = 0;
			if(list.size()>0) {
				for(Record rec : list) {
					updateCount = random.nextInt(Integer.valueOf(count));//根据指定的范围随机增加收藏数		
					
					String D_ID = String.valueOf(rec.getInt("D_ID"));
					String modelJson = jedis.hmget("rooms", D_ID).get(0);
					FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
					model.setD_CollectionCount((int)updateCount);
					TypeUtils.compatibleWithFieldName = true;
					jedis.hset("rooms", D_ID, JSON.toJSONString(model));
				}
			}
			
			SystemConfig.collectionConfig.put(id, count);//存放收藏数据，使下次点击可以直接读取			
		}
		
		return JsonKit.toDoubleJson("true", "ok");
	}
	/**
	 * 收藏全部清空
	 * @return
	 */
	public String ClearAllCollection() {
		//int result = dao.update("update room set D_CollectionCount=0,E_CollectionCount=0,D_Operation=null");
		int result = dao.update("update room set D_CollectionCount=0 or E_CollectionCount");//清除全部收藏D_CollectionCount，E_CollectionCount
		if(result>0) {
			SystemConfig.collectionConfig.clear();//清空收藏缓存
			return JsonKit.toDoubleJson("true", "ok");
		}
		return JsonKit.toDoubleJson("false", "sorry");
	}
	//收藏全部清空  reids 包括rooms 和  userShouCang
	public String ClearAllCollectionForRedis() {
		int result =1;
		List<String> list = jedis.hvals("rooms");//取出所有房源
		for(int i=0;i<list.size();i++) {
			FangYuanModel model = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});			
			model.setD_CollectionCount(0);
			model.setE_CollectionCount(0);					
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));							
		}
		if(jedis.exists("userShouCang")) {
			jedis.del("userShouCang");
		}
		if(result>0) {
			SystemConfig.collectionConfig.clear();//清空收藏缓存
			return JsonKit.toDoubleJson("true", "ok");
		}
		return JsonKit.toDoubleJson("false", "sorry");
	}
	/**
	 * 假收藏清空
	 * @return
	 */
	public String ClearJiaCollection() {
		//int result = dao.update("update room set D_CollectionCount=0,E_CollectionCount=0,D_Operation=null");
		int result = dao.update("update room set D_CollectionCount=0");//清除假收藏D_CollectionCount
		if(result>0) {
			SystemConfig.collectionConfig.clear();//清空收藏缓存
			return JsonKit.toDoubleJson("true", "ok");
		}
		return JsonKit.toDoubleJson("false", "sorry");
	}
	//清空假收藏 redis
	public String ClearJiaCollectionForRedis() {
		int result =1;
		List<String> list = jedis.hvals("rooms");//取出所有房源
		for(int i=0;i<list.size();i++) {
			FangYuanModel model = JSON.parseObject(list.get(i), new TypeReference<FangYuanModel>() {});			
			model.setD_CollectionCount(0);
			TypeUtils.compatibleWithFieldName = true;
			jedis.hset("rooms", String.valueOf(model.getD_ID()), JSON.toJSONString(model));							
		}
		if(result>0) {
			SystemConfig.collectionConfig.clear();//清空收藏缓存
			return JsonKit.toDoubleJson("true", "ok");
		}
		return JsonKit.toDoubleJson("false", "sorry");
	}
	
	/**
	 * 获取之前收藏数量
	 * @param type
	 * @param key
	 * @return
	 */
	public String dbClickGetValue(String type,String key) {
		int count =0;
		if("1".equals(type)) {//单个房源
			count = dao.queryForInt(String.format("select D_CollectionCount from room where D_ID=%d limit 1", Integer.valueOf(key)));			
		}else {//楼栋 单元 套型
			if(SystemConfig.collectionConfig.containsKey(key)) {
				count = Integer.parseInt(SystemConfig.collectionConfig.get(key));
			}
		}
		
		return JsonKit.toDoubleJsonForInt("true", count);
	}
	// redis
	public String dbClickGetValueForRedis(String type,String key) {
		int count =0;
		if("1".equals(type)) {//单个房源
			String modelJson = jedis.hmget("rooms", key).get(0);
			FangYuanModel  model = JSON.parseObject(modelJson, new TypeReference<FangYuanModel>() {});
			count = model.getD_CollectionCount();
		}else {//楼栋 单元 套型
			if(SystemConfig.collectionConfig.containsKey(key)) {
				count = Integer.parseInt(SystemConfig.collectionConfig.get(key));
			}
		}
		
		return JsonKit.toDoubleJsonForInt("true", count);
	}
	public ResponseEntity<byte[]> downloadRoomCollection() throws Exception{
		//String sql = String.format("select D_ID,D_BanName,D_RoomNo,E_CollectionCount from room");
		String sql = "select * from room";
		
		List<FangYuanModel> model = fyDao.queryForFangYuanList(sql);		
		if(model==null || model.size()==0) {
		    	return null;
		}else {
			TreeMap<String,List<FangYuanModel>> louDongMap= model.stream().collect(Collectors.groupingBy(FangYuanModel::getD_BanName,TreeMap::new,Collectors.toList()));
			//收藏集合
			List<RoomCollectionEntity> RoomCollectionList= dao.queryForRoomCollectionEntityList("select c.FieldId,u.D_Name,u.D_Tel,u.D_Card from t_collection as c JOIN t_user as u on c.UserName=u.D_Tel");
			TreeMap<Integer,List<RoomCollectionEntity>> RoomCollectionMap= RoomCollectionList.stream().collect(Collectors.groupingBy(RoomCollectionEntity::getRoomId,TreeMap::new,Collectors.toList()));
			
			for (Entry<String, List<FangYuanModel>> entry : louDongMap.entrySet()) {
				List<FangYuanModel> louDongModel = entry.getValue();//取一个楼栋数据
				for(FangYuanModel fyModel:louDongModel) {//遍历楼栋房源
					if(RoomCollectionMap.containsKey(fyModel.getD_ID())){
						List<RoomCollectionEntity> roomColleList = RoomCollectionMap.get(fyModel.getD_ID());
						StringBuilder sb = new StringBuilder();
						for(RoomCollectionEntity  rce:roomColleList) {
							sb.append(String.format("姓名:%s 手机:%s 身份证:%s;", rce.getName(),rce.getTel(),rce.getCardId()));
						}
						fyModel.setMsg(sb.toString());
					}
				}
			}
			HSSFWorkbook workbook = writeToExcel(louDongMap);
			
			return DownLoadKit.exportExcel(workbook, "收藏数据");
		}
		

	}
	public  HSSFWorkbook  writeToExcel(TreeMap<String,List<FangYuanModel>> louDongMap) throws Exception {
		
		HSSFWorkbook workbook = new HSSFWorkbook();  // 创建工作簿对象  
		for (Entry<String, List<FangYuanModel>> entry : louDongMap.entrySet()) {
			List<FangYuanModel> louDongModel = entry.getValue();//取一个楼栋数据
			HSSFSheet sheet = workbook.createSheet(entry.getKey()); //创建一个列表
			//创建标题行
			HSSFRow rowm = sheet.createRow(0);	
			rowm.createCell(0).setCellValue("楼栋");
			rowm.createCell(1).setCellValue("单元");
			rowm.createCell(2).setCellValue("房间号");
			rowm.createCell(3).setCellValue("收藏数量");
			rowm.createCell(4).setCellValue("收藏信息");
			//创建数据行
			int i=1;
			for(FangYuanModel fyModel:louDongModel) {//遍历楼栋房源
			    rowm = sheet.createRow(i);	
				rowm.createCell(0).setCellValue(fyModel.getD_BanName());
				rowm.createCell(1).setCellValue(fyModel.getD_Unit());
				rowm.createCell(2).setCellValue(fyModel.getD_RoomNo());
				rowm.createCell(3).setCellValue(fyModel.getE_CollectionCount());
				rowm.createCell(4).setCellValue(fyModel.getMsg());
				i++;
			}			
		}
		return workbook;
	}
	
}
